package com.iss.apartmentmanage.config.security;

import com.alibaba.fastjson.JSON;
import com.iss.apartmentmanage.model.MyResponseData;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class SelfAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        MyResponseData responseBody = new MyResponseData();
        if (e instanceof BadCredentialsException) {
            //密码错误
            responseBody.setStatus("444");
            responseBody.setMsg("1-passwordError-密码错误");
        }else if (e instanceof DisabledException) {
            //账号不可用
            responseBody.setStatus("444");
            responseBody.setMsg("2账号不可用");
        } else if (e instanceof InternalAuthenticationServiceException) {
            //用户不存在
            responseBody.setStatus("444");
            responseBody.setMsg("3用户不存在");
        }else{
            //其他错误
            responseBody.setStatus("444") ;
            responseBody.setMsg("4-otherError");
        }

        httpServletResponse.getWriter().write(JSON.toJSONString(responseBody));
    }
}
